package com.gpStudy.Netty.IO.BIO.tomcat;

import com.gpStudy.Netty.IO.BIO.tomcat.http.GPRequest;
import com.gpStudy.Netty.IO.BIO.tomcat.http.GPResponse;
import com.gpStudy.Netty.IO.BIO.tomcat.http.GPServlet;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/*
    //J2EE 标准
    //Servlet
    //Request
    //Response


    1、配置启动端口，默认 8080， ServerSeockt   IP:localhost
    2. 配置web.xml 自己写的 serrlet 继承 HttpServlet
          servlet-name
          servlet-class
          url-pattern

    3. 读取配置，url-pattern 和 servlet 建立一个映射关系
          Map  servletMapping


    4. Http请求，发送的数据就是 字符串，有规律的
          从浏览器的控制台请求中可以看出，请求头的信息  其实也是一段固定格式的字符串


     5.从协议内容中拿到 URL，把相依的 servlet 用反射进行实例化

     6. 调用实例化对象的service()方法，执行具体的逻辑 doGet()/doPost() 方法
     7. Request（InputStream）/ Response(OutputStream)
 */
public class GPTomcat {

    private int port = 8080;

    private ServerSocket server;

    private Map<String, GPServlet> servletMapping = new HashMap<>();

    private Properties webxml = new Properties();

    public void init(){

        try {

            String WEB_INF = this.getClass().getResource("/").getPath();
            FileInputStream fis = new FileInputStream(WEB_INF + "web.properties");

            webxml.load(fis);

            for (Object k : webxml.keySet()){
                String key = k.toString();
                if (key.endsWith(".url")) {
                    String url = webxml.getProperty(key);
                    String serverName = key.replaceAll("\\.url$", "");
                    String className = webxml.getProperty(serverName + ".className");

                    GPServlet gpServlet = (GPServlet) Class.forName(className).newInstance();
                    servletMapping.put(url, gpServlet);

                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }

    public void start(){

        init();

        try {
            server = new ServerSocket(this.port);
            System.out.println("GPTomcat 已启动监听，端口：" + this.port);

            while (true){
                Socket socket = server.accept();
                process(socket);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void process(Socket socket) {
        try {
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();

            GPRequest gpRequest = new GPRequest(inputStream);
            GPResponse gpResponse = new GPResponse(outputStream);

            String url = gpRequest.getUrl();
            if (servletMapping.containsKey(url)){
                servletMapping.get(url).service(gpRequest, gpResponse);
            }else{
                gpResponse.write("404 - Not Found !");
            }

            outputStream.flush();
            outputStream.close();

            inputStream.close();
            socket.close();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new GPTomcat().start();
    }
}
